package com.android.unipluginpicturewater;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.UiThread;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taobao.weex.adapter.URIAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;

/**
 * Description: UniPlugin-Hello-AS
 * Author:     yangtong<br>
 * Date:    2023/5/15    13:54
 * Version:
 * Update:
 */
public class PictureWaterModule extends UniModule {
    private final String TAG = "PictureWaterModule";
    private final String prefixStr = "data:image/png;base64,";
    WaterMaker waterMaker;
    private boolean outputPath;
    private JSONObject configOption;
    private boolean rotateWater;
    private float compressSize;

    @SuppressLint("NewApi")
    @UniJSMethod
    public void getPermission() {
        ((Activity) mUniSDKInstance.getContext()).requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 99);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 99) {
            if (grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {

            }
        }
    }

    @UniJSMethod(uiThread = true)
    public long sizeAtPath(String path) {
        Uri uri = mUniSDKInstance.rewriteUri(Uri.parse(path), URIAdapter.FILE);
        String path1 = filtrationPath(uri.toString());
        File file = new File(path1);
        return file.length();
    }

    @UniJSMethod(uiThread = true)
    public void addWaterForPath(JSONObject options, UniJSCallback callback) {
        List paths = options.getJSONArray("photos");
        JSONObject jsonObject = (JSONObject) paths.get(0);
        configPamars(options);
        Uri uri = mUniSDKInstance.rewriteUri(Uri.parse(jsonObject.getString("path")), URIAdapter.FILE);
        List<JSONObject> data = new ArrayList<>();
        if (jsonObject.containsKey("contents")){
            JSONArray array1 = jsonObject.getJSONArray("contents");
            for (int i = 0; i < array1.size(); i++) {
                JSONObject item = (JSONObject) array1.get(i);
                data.add(item);
            }
        }
        String path = filtrationPath(uri.toString());
        waterMaker.waterMarkBitmap(configOption, path, false, data, rotateWater, positionType(options.getString("waterType")), options.getString("RotateCustomText"), compressSize);
        String file = waterMaker.getPath();
        String base64Str = prefixStr + waterMaker.getBase64String();
        JSONObject result = new JSONObject();
        if (outputPath) {
            result.put("path", file);
        } else {
            clearCacheWithFilePath(file);
            result.put("path", "");
        }
        result.put("base64", base64Str);
        JSONArray array = new JSONArray();
        array.add(result);
        callback.invokeAndKeepAlive(array);
    }

    //    base64绘制
    @UniJSMethod(uiThread = true)
    public void addWaterForBase64(JSONObject options, UniJSCallback callback) {
        List paths = options.getJSONArray("photos");
        JSONObject jsonObject = (JSONObject) paths.get(0);
        configPamars(options);
        List<JSONObject> data = new ArrayList<>();
        JSONArray array1 = jsonObject.getJSONArray("contents");
        for (int i = 0; i < array1.size(); i++) {
            JSONObject item = (JSONObject) array1.get(i);
            data.add(item);
        }
        String path = jsonObject.getString("path");
        waterMaker.waterMarkBitmap(configOption, path, true, data, rotateWater, positionType(options.getString("waterType")), options.getString("RotateCustomText"), compressSize);
        String file = waterMaker.getPath();
        String base64Str = prefixStr + waterMaker.getBase64String();
        JSONObject result = new JSONObject();
        if (outputPath) {
            result.put("path", file);
        } else {
            clearCacheWithFilePath(file);
            result.put("path", "");
        }
        result.put("base64", base64Str);
        JSONArray array = new JSONArray();
        array.add(result);
        callback.invokeAndKeepAlive(array);
    }

    private void configPamars(JSONObject options) {
        configOption = null;
        if (options.containsKey("configStyle") && options.getJSONObject("configStyle") != null) {
            configOption = options.getJSONObject("configStyle");
        }
        if (waterMaker == null) {
            waterMaker = new WaterMaker(mUniSDKInstance.getContext());
        }
        rotateWater = false;
        if (options.containsKey("rotateWater") && options.getBooleanValue("rotateWater")) {
            rotateWater = true;
        }
        outputPath = false;
        if (options.containsKey("outputPath") && options.getBooleanValue("outputPath")) {
            outputPath = true;
        }
        compressSize = 1.0f;
        if (options.containsKey("compressSize") && options.getFloatValue("compressSize") > 0) {
            compressSize = options.getFloatValue("compressSize");
        }
    }

    @UniJSMethod(uiThread = true)
    public boolean clearCacheWithFilePath(String filePath) {
        if (filePath == null || TextUtils.isEmpty(filePath)) {
            return false;
        }
        File file = new File(filePath);
        boolean delete = file.delete();
        return delete;
    }

    private String filtrationPath(String oldPath) {
        if (oldPath.startsWith("file:///")) {
            return oldPath.replace("file:///", "/");
        } else if (oldPath.startsWith("file://")) {
            return oldPath.replace("file://", "/");
        } else if (oldPath.startsWith("file:/")) {
            return oldPath.replace("file:/", "/");
        } else {
            return oldPath;
        }
    }

    //    初始化属性
    private int positionType(String str) {
        if (str == null || TextUtils.isEmpty(str))return 2;
        int i = 2;
        if (str.equals("leftBottom")) {
            i = 2;
        } else if (str.equals("leftTop")) {
            i = 0;
        } else if (str.equals("rightTop")) {
            i = 1;
        } else if (str.equals("rightBottom")) {
            i = 3;
        }
        return i;
    }
}
